package com.android.multiplesmart.activity;

import android.Manifest;
import android.animation.ObjectAnimator;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.provider.Settings;
import android.text.InputFilter;
import android.text.Spanned;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.databinding.DataBindingUtil;

import com.android.multiplesmart.DemoApplication;
import com.android.multiplesmart.R;
import com.android.multiplesmart.adapter.GridLanguageAdapter;
import com.android.multiplesmart.api.Api;
import com.android.multiplesmart.api.ApiUrl;
import com.android.multiplesmart.api.BaseHttp;
import com.android.multiplesmart.bean.AppVersionBean;
import com.android.multiplesmart.bean.LaguageAllBean;
import com.android.multiplesmart.bean.LanguageDataBean;
import com.android.multiplesmart.bean.LanguageTypeBean;
import com.android.multiplesmart.bean.LanguageTypeDataBean;
import com.android.multiplesmart.bean.MessageEvent;
import com.android.multiplesmart.bean.SecretKeyBean;
//import com.android.multiplesmart.databinding.ActivitysSelectLanguageBinding;
import com.android.multiplesmart.bean.Servicess;
import com.android.multiplesmart.dialog.SetUserNameDialog;
import com.android.multiplesmart.downfiles.DownloadUtil;
import com.android.multiplesmart.downfiles.FileUtil;
import com.android.multiplesmart.downfiles.FileVo;
import com.android.multiplesmart.downfiles.RxUtils;
import com.android.multiplesmart.utils.AesUtils;
import com.android.multiplesmart.websocket.JWebSocketClient;
import com.android.multiplesmart.websocket.JWebSocketClientService;
import com.daimajia.numberprogressbar.NumberProgressBar;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import com.schillerchina.baselibrary.constans.AppConstants;
import com.schillerchina.baselibrary.network.App;
import com.schillerchina.baselibrary.network.RetrofitHandler;
import com.schillerchina.baselibrary.utils.GsonUtil;
import com.schillerchina.baselibrary.utils.Pref;
import com.schillerchina.baselibrary.utils.ToastUtil;

import com.tencent.smtt.sdk.WebView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.io.File;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class SelectLanguageActivitys extends BaseActivity implements BaseHttp.OnCallBack,View.OnLongClickListener{
    //    https://uat.metalingual.com.cn/upload/doc/1785207918534975489/1785207924868374529.docx
//    private ActivitysSelectLanguageBinding binding;
    //显示
    //    WebSocket服务绑定信息
    private JWebSocketClient client;
    private JWebSocketClientService.JWebSocketClientBinder binder;
    private JWebSocketClientService jWebSClientService;
    public String action;

    private boolean isBind = false;

    private ArrayList<LanguageDataBean> studentLanguages = new ArrayList<>();

    private String userName;
    private Api api;
    private EditText editText;
    private TextView next,skip;

    public  static   SelectLanguageActivitys activitys;
    ///临时数据
    // {"Cmd":"ClassroomInfo","Data":{"Course":"汉语教学","Teacher":"光辉",
    // "TeacherLanguage":{"LanguageCode":"zh-CN","LanguageName":"中文","LanguageEnName":"Chinese"},
    // "StudentLanguages":[{"LanguageCode":"zh-CN","LanguageName":"中文","LanguageEnName":"Chinese"}
    // ,{"LanguageCode":"en-GB","LanguageName":"英语（英国）","LanguageEnName":"English (United Kingdom)"}
    // ,{"LanguageCode":"en-US","LanguageName":"英语（美国）","LanguageEnName":"English (United States)"}
    // ,{"LanguageCode":"ja-JP","LanguageName":"日语（日本）","LanguageEnName":"Japanese (Japan)"}]}
    // ,"Time":"2024-04-25 10:43:24"}

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activitys_select_language);
//        binding = DataBindingUtil.setContentView(this, R.layout.activitys_select_language);

        activitys=this;
//        userName=getxIntent().getStringExtra("name");

        initView();
        initListener();
        EventBus.getDefault().register(this);
//        showChangeUserName();
        //模拟数据
//        moni();
        //每次删除上次下载的文件
        String path= FileUtil.getCachePath(SelectLanguageActivitys.this);
        File file=new File(path);
        if(file.exists()){
            File[] files= file.listFiles();
            if(files.length>0){
                for (int i=0;i<files.length;i++){
                    files[i].delete();
                }
            }
        }

        RetrofitHandler.init(ApiUrl.base);
        api=RetrofitHandler.getRetrofit().create(Api.class);
        Map<String,Object> map=new HashMap<>();
        map.put("en",0);
        map.put("type",0);
        languageName(map,0,ApiUrl.languageName);
//        Intent intent=new Intent(this,WebViewActivity.class);
//        startActivity(intent);
//        moni();
        String id= getAndroidId(getApplicationContext());
        System.out.println(getExternalCacheDir().getPath()+"安装包路径"+id);


//        Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS);
//        intent.setData(Uri.parse("package:" +getPackageName()));
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        startActivity(intent);


    }
    @Override
    protected void onResume() {
        super.onResume();
//        Intent intent = new Intent();
//        intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
//        startActivityForResult(intent, 1);
//        if (!checkPermission(this,PERMS_WRITE)){
//            requestPermission(this,"Open authority",1,PERMS_WRITE);
//        }else{
////            ToastUtil.showToast(this,"Open");
//        }

    }


    //接收事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void ReceiveMessage1(MessageEvent msg){
//            if (msg.message){
//                ToastUtil.showToast(" Kernel loaded successfully");
//                DemoApplication.getHandlerUtils().saveCrashInfo2File("Kernel loaded successfully");
////                xianshi.setText("Kernel loaded successfully");
//            }else {
//                ToastUtil.showToast(" Kernel loading failure");
//                DemoApplication.getHandlerUtils().saveCrashInfo2File("Kernel loading failure");
//                xianshi.setText("Kernel loading failure");
//            }
    }


    /**
     * 请求信息
     * @param map
     * @param state
     */
    private void languageName(Map<String,Object>map,int state,String url){
        BaseHttp.getBaseHttp()
                .setUrl(url)
                .setMap(map)
                .setOnCallBack(this)
                .setState(state)
                .request(api);
    }


    private void mic(int state,String url){
        BaseHttp.getBaseHttp()
                .setUrl(url)
                .setOnCallBack(this)
                .setState(state)
                .requests(api);
    }


    public  void  start(){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                languageTypeBean=null;
                course.setText("The course has not started yet");
                teachername.setText("");
            }
        });
    }
    public  void  stopcourse(){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                course.setText("The course has not started yet");
                teachername.setText("");
            }
        });

    }



    private void moni() {
        languageTypeBean=new LanguageTypeBean();
        LanguageTypeDataBean languageTypeDataBean=new LanguageTypeDataBean();
        LanguageDataBean languageDataBean=new LanguageDataBean();
        languageDataBean.setLanguageCode("zh-Hans");
        languageDataBean.setLanguageName("中文");
        languageDataBean.setLanguageEnName("Chinese");
        languageTypeDataBean.setTeacherLanguage(languageDataBean);
        languageTypeDataBean.setTeacher("光辉");
        languageTypeDataBean.setCourse("汉语教学");
        List<LanguageDataBean > list=new ArrayList<>();
        LanguageDataBean languageDataBean1=new LanguageDataBean();
        languageDataBean1.setLanguageCode("en");
        languageDataBean1.setLanguageName("英语（英国）");
        languageDataBean1.setLanguageEnName("English (United Kingdom)");
        LanguageDataBean languageDataBean2=new LanguageDataBean();
        languageDataBean2.setLanguageCode("ja");
        languageDataBean2.setLanguageName("日语（日本）");
        languageDataBean2.setLanguageEnName("Japanese (Japan)");
        list.add(languageDataBean);
        list.add(languageDataBean1);
        list.add(languageDataBean2);
        languageTypeDataBean.setStudentLanguages(list);
        languageTypeBean.setData(languageTypeDataBean);
        //binding.txtTeacher.setText("教师：" + languageTypeBean.getData().getTeacher() + "--课程：" + languageTypeBean.getData().getCourse());
        if (languageTypeBean.getData().getStudentLanguages() != null) {
            studentLanguages.clear();
            studentLanguages.addAll(languageTypeBean.getData().getStudentLanguages());
//            GridLanguageAdapter(studentLanguages);
        }
    }

    private void showChangeUserName() {
        SetUserNameDialog setUserNameDialog = new SetUserNameDialog(SelectLanguageActivitys.this);
        setUserNameDialog.setOnSureButtonOnClickListener(new SetUserNameDialog.ISureButtonOnclick() {
            @Override
            public void SureButtonOnClick(String user_name) {
                userName = user_name;
                AppConstants.USERNAME = user_name;
//              Pref.put(AppConstants.USER_NAME, userName);
//                binding.txtStudent.setText("学生：" + user_name);
            }
        });
        setUserNameDialog.show();
    }


    /**
     * SPP蓝牙连接广播监听
     */
    private  LanguageTypeBean languageTypeBean;
    private  String message;
    private BroadcastReceiver mBluetoothReceiver = new BroadcastReceiver() {

        //        @RequiresApi(api = Build.VERSION_CODES.P)
        @Override
        public void onReceive(Context context, final Intent intent) {
            action = intent.getAction();
            if (action.equals(AppConstants.WEBSOCKET_SNED_MESSAGE_ACTION)) {//PC端主动推送教室和语种数据
//               WebSocket收到数据
                message = intent.getStringExtra("message");
                try {
                    Gson gson = new Gson();
                    Type type = new TypeToken<LanguageTypeBean>() {
                    }.getType();
                    languageTypeBean = gson.fromJson(message, type);
                    Log.i("zzg", "message:" +languageTypeBean.getData().getSessionId()
                    );
                    course.setText(languageTypeBean.getData().getCourse());
                    teachername.setText(languageTypeBean.getData().getTeacher());
                    //binding.txtTeacher.setText("教师：" + languageTypeBean.getData().getTeacher() + "--课程：" + languageTypeBean.getData().getCourse());
//                  if (languageTypeBean.getData().getStudentLanguages() != null) {
//                            studentLanguages.clear();
//                            studentLanguages.addAll(languageTypeBean.getData().getStudentLanguages());
//                            GridLanguageAdapter(studentLanguages);
//                  }
                } catch (Exception e) {
                    Log.i("zzg", "e:" + e.toString());
                }


            }else if(action.equals(AppConstants.onOpen)){
                ToastUtil.showToast(SelectLanguageActivitys.this,"Connection successful");
            }else  if (action.equals(AppConstants.WEBSOCKET_COLSE_TEACHING_ACTION)){//PC主动推送结束授课信号
                if (Servicess.getService().getState()==1){
                    String  languageCodess =Pref.getString(AppConstants.languageCodess,"");
                    stopcourse();
//                  message = intent.getStringExtra("message");
                    if (languageCodess.equals("")){
                        ToastUtil.showToast("Get languageCodes error");
                        return;
                    }
                    Intent intent1=new Intent(SelectLanguageActivitys.this,CodeActivity.class);
                    intent1.putExtra("Url",intent.getStringExtra("message"));
                    intent1.putExtra("code",languageCodess);
                    startActivity(intent1);
                }
            }
        }
    };

//    private void GridLanguageAdapter(ArrayList<LanguageDataBean> studentLanguages) {
//        GridLanguageAdapter gridLanguageAdapter = new GridLanguageAdapter(studentLanguages);
//        binding.gridLanguage.setAdapter(gridLanguageAdapter);
//        binding.gridLanguage.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                LanguageDataBean languageDataBean = (LanguageDataBean) view.getTag();
//                Intent intent = new Intent(SelectLanguageActivitys.this,MainActivitys.class);
//                if (userName.equals("")){
//                    userName=languageDataBean.getLanguageEnName()+"_学生1";
//
//                }
//                intent.putExtra(AppConstants.USER_NAME, userName);
//                intent.putExtra(AppConstants.STUDENT_LANGUAGES, GsonUtil.GsonString(studentLanguages));
//                intent.putExtra(AppConstants.SELECT_LANGUAGES, GsonUtil.GsonString(languageDataBean));
//                intent.putExtra(AppConstants.TEACHER_CURRICULUM, GsonUtil.GsonString(languageTypeBean));
//                intent.putExtra(AppConstants.All_LANGUAGES,allLaguage);
//                startActivity(intent);
//                Log.i("zzg", "languageDataBean:" + languageDataBean.getLanguageName());
//            }
//        });
//    }


    @Override
    protected void onStart() {
        super.onStart();
        System.out.println("广播");

    }


    /**
     * 初始化WebSocket服务
     */
    private void initWebSocket() {
//        System.out.println("广播一");
//        Log.e("JWebSocketClientService", "广播一");
        //注册SPP蓝牙广播
        //启动服务
        startJWebSClientService();
        //绑定服务
        bindService();
    }


    /**
     * 绑定服务
     */
    private void bindService() {
        Intent bindIntent = new Intent(this, JWebSocketClientService.class);
        isBind = bindService(bindIntent, serviceConnection, BIND_AUTO_CREATE);
    }

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            Log.e("MainTestActivity", "服务与活动成功绑定");
            binder = (JWebSocketClientService.JWebSocketClientBinder) iBinder;
            jWebSClientService = binder.getService();
            client = jWebSClientService.client;
            jWebSClientService.setStates(1);
            Servicess.getService().setService(jWebSClientService);

        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.e("MainTestActivity", "服务与活动成功断开");
        }
    };

    /**
     * 启动服务（websocket客户端服务）
     */
    private void startJWebSClientService() {
        Intent intent = new Intent(this, JWebSocketClientService.class);
        startService(intent);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sub:
                officeSaveName="zhihui.apk";
                downloadUtil= DownloadUtil.get();
                downLoadFile(appVersionBean.getResult().getAppFilePath());
                break;
            case R.id.colse:
                alertDialog.cancel();
                break;
            case R.id.subTwo:
                if(textpassword.getText().toString().equals("123456")){
                    settinglayoutone.setVisibility(View.GONE);
                    textpassword.setVisibility(View.GONE);
                    settinglayouttwo.setVisibility(View.VISIBLE);
                }else {
                    ToastUtil.showToast(this,"Password error");
                }
                break;
            case R.id.colseTwo:
                alertDialog.cancel();
                break;
            case R.id.subThree:
                if(url.getText().toString().equals("")){
                    ToastUtil.showToast(this,"set up Ip");
                    return;
                }
                DemoApplication.getHandlerUtils().saveCrashInfo2File("点击配置弹窗上的确定");
                colseService();
                String ip=  url.getText().toString();
                String ports= port.getText().toString();
                if (port.getText().toString().equals("")){
                    AppConstants.setAddress("ws://"+ip);
                }else {
                    AppConstants.setAddress("ws://"+ip+":"+ports);
                }
                Pref.put(AppConstants.WS_ADDRESS, AppConstants.getAddress());
                alertDialog.cancel();
                restartApp();
                break;
            case R.id.colseThree:
                alertDialog.cancel();
                break;
            case R.id.next:
                String name=editText.getText().toString().trim();
                if (name.equals("")){
                    ToastUtil.showToast("Fill in your name");
                    return;
                }
                String names=editText.getText().toString().trim();
                initen(message,names);
                System.out.println(names+"获取美容");
                break;
            case R.id.skip:
                initen(message,"");
                break;
            case R.id.colseapp:
                colseService();
                restartApp();
                break;
            default:
                break;
        }
    }

    private void initen(String message,String   name){
        if (message==null || languageTypeBean==null  ){
            ToastUtil.showToast("Abnormal connection or teacher not clicking on class");
            return;
        }
        if ( languageTypeBean.getData()==null  ){
            ToastUtil.showToast("Abnormal connection or teacher not clicking on class");
            return;
        }
        DemoApplication.getHandlerUtils().saveCrashInfo2File("点击SelectLanguageActivitys确定按钮");
        Pref.put(AppConstants.name,name);
        Pref.put(AppConstants.allLaguage,allLaguage);
//        colseService();
        Intent intent=new Intent(this,LoginActivity.class);
        intent.putExtra("message",message);
//        intent.putExtra("name",name);
//        intent.putExtra("allLaguage",allLaguage);
        startActivity(intent);
    }

    void  colseService(){
        if (isBind) {
            jWebSClientService.closeConnect();
            isBind=false;
            Log.e("MainTestActivity", "执行了销毁");
            unregisterReceiver(mBluetoothReceiver);
            unbindService(serviceConnection);
            Intent intent=new Intent(this,JWebSocketClientService.class);
            stopService(intent);
        }
    }



    private void restartApp() {
//        Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
//        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//        startActivity(intent);
        System.exit(0);
    }

    @Override
    public void initListener() {
        //binding.txtStudent.setOnClickListener(this);
        setting.setOnLongClickListener(this);
        next.setOnClickListener(this);
        skip.setOnClickListener(this);
        colseapp.setOnClickListener(this);
    }
    private LinearLayout setting;
    private TextView course,teachername,textVer,colseapp,xianshi;
    @Override
    public void initView() {
        editText=findViewById(R.id.textStuen);
        next=findViewById(R.id.next);
        skip=findViewById(R.id.skip);
        setting=findViewById(R.id.setting);
        course=findViewById(R.id.course);
        teachername=findViewById(R.id.teachername);
        textVer=findViewById(R.id.textver);
        colseapp=findViewById(R.id.colseapp);
        xianshi=findViewById(R.id.xianshi);




        editText.setFilters(new InputFilter[]{new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                if (source.toString().contains("\n")) {
                    return ""; // 过滤换行
                }
                return null; // 允许输入
            }
        }});

        IntentFilter discoveryFilter = new IntentFilter();
        discoveryFilter.addAction(AppConstants.onOpen);
        discoveryFilter.addAction(AppConstants.WEBSOCKET_SNED_MESSAGE_ACTION);
        discoveryFilter.addAction(AppConstants.WEBSOCKET_COLSE_TEACHING_ACTION);
        registerReceiver(mBluetoothReceiver, discoveryFilter);
        initWebSocket();
        File  file=getExternalFilesDir("text");

        File  file2 = new File(file, "errorLog.txt");
        System.out.println(file2.getAbsolutePath()+"获取路径");
    }

    private String allLaguage;
    private AppVersionBean appVersionBean;
    private String officeSaveName="";
    private DownloadUtil downloadUtil;
    @Override
    public void onSusses(Call<String> call, String value,int state) {
        if (state==0){///获取所有语言
            allLaguage=value;
            mic(1,ApiUrl.mic);
        }else if (state==1){///获取微软的key
            SecretKeyBean  secretKeyBean=GsonUtil.GsonToBean(value,SecretKeyBean.class);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                String s=AesUtils.decrypt(secretKeyBean.getResult().get(0),"2023GeziizeG3202");
                String s1=AesUtils.decrypt(secretKeyBean.getResult().get(1),"2023GeziizeG3202");
                AppConstants.setKey(s1,s);
            }
            mic(2,ApiUrl.app);

        }else if (state==2){///获取App版本号
            try {
                // 获取PackageManager实例
                PackageManager packageManager = getPackageManager();
                // getPackageName()是你当前类的包名，0代表是获取版本信息
                PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
                // 获取versionName
                String versionName = packageInfo.versionName;
                // 输出versionName

                appVersionBean=GsonUtil.GsonToBean(value,AppVersionBean.class);
                Double locald =Double.parseDouble(versionName);
                textVer.setText("v"+versionName);
                Double d =Double.parseDouble(appVersionBean.getResult().getAppVersion());
                Log.d("呼气数据", "versionName: " + versionName+"----"+d);
                if (d>locald){
                    View view=  alert(R.layout.progress);
                    Button sub= view.findViewById(R.id.sub);
                    Button colse= view.findViewById(R.id.colse);
                    number_progress_bars= view.findViewById(R.id.number_progress_bars);
                    sub.setOnClickListener(this);
                    colse.setOnClickListener(this);
                }
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }

        }
    }


    /**
     * 下载文件
     */
    FileVo fileVo=new FileVo();
    private  void   downLoadFile(String pdf_url){
        Observable.create(new ObservableOnSubscribe<FileVo>() {
            @Override
            public void subscribe(final ObservableEmitter<FileVo> e) throws Exception {
                String path= FileUtil.getCachePaths(SelectLanguageActivitys.this);
                downloadUtil.download(pdf_url, path,
                        officeSaveName,
                        new DownloadUtil.OnDownloadListener() {
                            @Override
                            public void onDownloadSuccess(File file) {
                                fileVo.setFile(file);
                                e.onNext(fileVo);
                                e.onComplete();
                            }
                            @Override
                            public void onDownloading(int progress) {
                                showProgress(progress);
                            }
                            @Override
                            public void onDownloadFailed(Exception e) {
                            }
                        });
            }

        }).compose(RxUtils.schedulersTransformer()).subscribe(new Consumer<FileVo>() {
            @Override
            public void accept(FileVo fileVo) {
                alertDialog.cancel();
                Log.d("当前下载的进度","完成");
                showOffice(fileVo);
            }
        });
    }
    /**
     * 显示进度
     * @param progress
     */
    private   void   showProgress(final int  progress){
        Observable.just(progress)
                .compose(RxUtils.schedulersTransformer())
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer integer) throws Exception {
                        Log.d("当前下载的进度",""+progress);
                        number_progress_bars.setProgress(progress);
                    }
                });

    }
    Uri uri;
    void  showOffice(FileVo fileVo){
        Intent install =null;
        String type = "application/vnd.android.package-archive";
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            Intent intent =new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(fileVo.getFile()),"application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        } else {
            if(fileVo.getFile()!=null && fileVo.getFile().exists()){
                uri = FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", fileVo.getFile());
                //为其他APP授权访问内容URI的权限, 这是第一种授权
                install =new Intent(Intent.ACTION_INSTALL_PACKAGE);
                install.setData(uri);
                install.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                startActivity(install);
            }
        }
    }

    @Override
    public void onError(Call<String> cal, Throwable t,int state) {
        if (state==0){

        }else if (state==1){

        }else if (state==2){

        }
    }
    private NumberProgressBar  number_progress_bars;
    private AlertDialog alertDialog;
    private View   alert(int viewId){
        View view= LayoutInflater.from(this).inflate(viewId,null);
        alertDialog=new AlertDialog.Builder(this)
                .setView(view)
                .setCancelable(false)
                .create();
        alertDialog.show();
        return view;
    }
    LinearLayout settinglayoutone,settinglayouttwo;
    EditText textpassword,url,port;
    @Override
    public boolean onLongClick(View v) {
        switch (v.getId()){
            case R.id.setting:
                View view=alert(R.layout.passwrod);
                settinglayoutone=view.findViewById(R.id.settinglayoutone);
                settinglayouttwo=view.findViewById(R.id.settinglayouttwo);
                textpassword=view.findViewById(R.id.textpassword);
                url=view.findViewById(R.id.url);
                port=view.findViewById(R.id.port);

                String urls= Pref.getString(AppConstants.WS_ADDRESS,"");
                String[] strings=urls.split(":");
                System.out.println("JWebSocketClientService"+strings.length+"长度");
                if (strings.length>2){
                    url.setHint("默认Ip:"+strings[1].replace("//",""));
                    port.setHint("默认端口:"+strings[2]);
                }else {
                    url.setHint("默认Ip:"+strings[1].replace("//",""));
                    port.setHint("默认端口:");
                }

                Button subTwo= view.findViewById(R.id.subTwo);
                Button colseTwo= view.findViewById(R.id.colseTwo);
                Button subThree= view.findViewById(R.id.subThree);
                Button colseThree= view.findViewById(R.id.colseThree);
                subTwo.setOnClickListener(this);
                colseTwo.setOnClickListener(this);
                subThree.setOnClickListener(this);
                colseThree.setOnClickListener(this);
                break;
        }
        return true;
    }


    @Override
    public void onBackPressed() {
        // 禁用返回键，不执行任何操作
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    public  String getAndroidId(Context context) {
        return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
    }


}
